package com.jf.mall.web;

import com.jf.mall.domain.Furniture;
import com.jf.mall.domain.Page;
import com.jf.mall.service.FurnitureService;
import com.jf.mall.utils.DataUtils;
import com.jf.mall.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-09-26
 * Time:15:27
 */
@WebServlet(name = "FurnitureServlet", urlPatterns = "/manage/furnitureServlet")
public class FurnitureServlet extends BasicServlet {
    private FurnitureService furnitureService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        furnitureService = new FurnitureService();
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Furniture> furniture = furnitureService.getFurniture();
        req.setAttribute("furns", furniture);
        req.getRequestDispatcher("/views/admin/furn_manage.jsp").forward(req, resp);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Furniture furniture = DataUtils.copyParamToBean(req.getParameterMap(), Furniture.class);
        int i = furnitureService.saveFurniture(furniture);
        if (i == 1) {
            String pageNo = req.getParameter("page");
            resp.sendRedirect(req.getServletContext().getContextPath() + "/manage/furnitureServlet?action=page&page=" + pageNo);
        } else {
            if (i == -1) req.setAttribute("warning", "数据格式有误,添加失败!");
            req.getRequestDispatcher("/views/admin/furn_add.jsp").forward(req, resp);
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = DataUtils.parseInt(req.getParameter("id"), -1);
        furnitureService.deleteFurniture(id);
        String pageNo = req.getParameter("page");
        resp.sendRedirect(req.getServletContext().getContextPath() + "/manage/furnitureServlet?action=page&page=" + pageNo);
    }

    private void show(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = DataUtils.parseInt(req.getParameter("id"), -1);
        Furniture furniture = furnitureService.getFurniture(id);
        req.setAttribute("furn", furniture);
        //req.setAttribute("page", req.getParameter("page"));
        req.getRequestDispatcher("/views/admin/furn_update.jsp").forward(req, resp);
    }

    //private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //    Furniture furniture = DataUtils.copyParamToBean(req.getParameterMap(), Furniture.class);
    //    furnitureService.updateFurniture(furniture);
    //    String pageNo = req.getParameter("page");
    //    resp.sendRedirect(req.getServletContext().getContextPath() + "/manage/furnitureServlet?action=page&page=" + pageNo);
    //}
    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Furniture furniture = DataUtils.copyParamToBean(req.getParameterMap(), Furniture.class);
        String pageNo = req.getParameter("page");
        if (ServletFileUpload.isMultipartContent(req)) {
            //furniture = new Furniture();
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            fileUpload.setHeaderEncoding("UTF-8");
            try {
                List<FileItem> fileItems = fileUpload.parseRequest(req);
                String oldImgPath = null;
                String newImgPath = null;
                for (FileItem item : fileItems) {
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String value = item.getString("UTF-8");
                        switch (fieldName) {
                            case "id":
                                furniture.setId(DataUtils.parseInt(value, 0));
                                break;
                            case "name":
                                furniture.setName(value);
                                break;
                            case "maker":
                                furniture.setMaker(value);
                                break;
                            case "price":
                                furniture.setPrice(new BigDecimal(value));
                                break;
                            case "sale":
                                furniture.setSale(DataUtils.parseInt(value, 0));
                                break;
                            case "stock":
                                furniture.setStock(DataUtils.parseInt(value, 0));
                                break;
                            case "imgPath":
                                oldImgPath = value;
                                break;
                            case "page":
                                pageNo = value;
                                break;
                        }
                    } else {
                        newImgPath = WebUtils.saveFile("assets/images/product-image/", item, req);
                    }
                }
                String imgPath = oldImgPath;
                if (newImgPath != null) {
                    imgPath = newImgPath;
                    WebUtils.deleteFile(oldImgPath, req);
                }
                furniture.setImgPath(imgPath);
                furnitureService.updateFurniture(furniture);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        resp.sendRedirect(req.getServletContext().getContextPath() + "/manage/furnitureServlet?action=page&page=" + pageNo);
    }

    private void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNo = DataUtils.parseInt(req.getParameter("page"), 1);
        int pageSize = DataUtils.parseInt(req.getParameter("pageSize"), Page.DEFAULT_PAGE_SIZE);
        Page<Furniture> page = furnitureService.getFurniturePage(pageNo, pageSize);
        req.setAttribute("page", page);
        req.getRequestDispatcher("/views/admin/furn_manage.jsp").forward(req, resp);
    }
}
